// pages/screens/letter/letter.js
const regeneratorRuntime = getApp().globalData.regeneratorRuntime;
const LAST_CONNECTED_DEVICE = 'last_connected_device';
const tool = require("../../../utils/util");
const PrinterJobs = require('../comm/printerjobs');
const printerUtil = require('../comm/printerutil');
const util = require('../comm/util.js');
const screenresultservice = require('../../../apiservice/screen/screenresultservice');
const scResulthelper = require('./scResult.js');
const bluetoothBehaviors = require('bluetoothbehaviors');
const qrcodetxt = "http://weixin.qq.com/r/L0glPRPE3k6hrVde9x09"; //二维码内容


Component({
	behaviors: [bluetoothBehaviors],
	/**
	 * 页面的初始数据
	 */
	data: {
		schoolId: '',
		studentInfo: {},
		devices: [],
		connected: false,
		chs: [],
		dialogShow: false,
		//客户信息
		scinfo: {},
		//筛查判断
		scjudgeResult: [],
		//是否显示筛查判断
		scjudgeshow: false,
		//筛查ID
		scid: '',
		//裸眼视力
		nakedEye: {
			nakedEyeRight: '',
			nakedEyeLeft: '',
			visionRight: '',
			visionLeft: ''
		},
		//是否显示 裸眼视力项目
		nakedEyeshow: false,
		//矫正视力
		correctEye: {
			visionRight: '',
			visionLeft: ''
		},
		//是否显示 矫正视力项目
		correctEyeshow: false,
		//建议
		advise: {},
		//是否显示建议
		adviseshow: false,
		//屈光检查
		refractiveexamination: {},
		refractiveexaminationshow: false,
		//屈光度数检查
		dioptertest: {},
		dioptertestshow: false,

	},

	methods: {
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {
			let res = wx.getSystemInfoSync();
			 console.log(res);
			let that = this;
			let eventChannel = this.getOpenerEventChannel();
			wx.showLoading({
				title: "加载中...."
			})
			const lastDevice = wx.getStorageSync(LAST_CONNECTED_DEVICE);
			this.setData({
				schoolId: options.schoolId ? options.schoolId : "",
				scid: options.scid,
				lastDevice: lastDevice,
				platform: res.platform,
			});


			if (eventChannel) {
				eventChannel.on('acceptDataFromOpenerPage', function(data) {
					console.log("acceptDataFromOpenerPage", data.data);
					let scinfo = data.data;
					that.setData({
						scinfo: scinfo
					})

					let leadid = scinfo.leadid;
					// console.log('scid' + that.data.scid, ' leadid' + leadid)
					// console.log(that.data.scinfo);
					that.GetScreenResultsByScreenIdAndCustomerId(that.data.scid, leadid, that);
					// console.log("call onshow");
				})
			} else {
				wx.hideLoading();
			}


		},


		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function() {


			//蓝牙
	
			//debugger

		},

		writeBLECharacteristicValue() {
			let schoolId = this.data.schoolId;
			var scinfo = this.data.scinfo;
			var personInfo = [];
			let studentInfo = this.data.studentInfo;

			personInfo.push(`姓名:${scinfo.customername}`);
			if (scinfo.age) {
				personInfo.push("年龄:" + scinfo.age);
			}
			if (scinfo.sex) {
				personInfo.push(scinfo.sex == 0 ? '性别: 未知' : scinfo.sex == 1 ? '性别: 男' : '性别: 女');
			}
			if (schoolId) {
				if (studentInfo.hasOwnProperty("new_schoolName")) {
					personInfo.push(`学校:${studentInfo.new_schoolName}`);
				}
				if (studentInfo.hasOwnProperty("new_schoolName")) {
					personInfo.push(`班级号:${studentInfo.new_schoolName}`);
				}
			}
			let printerJobs = new PrinterJobs();
			let title = "眼部健康筛查结果通知单";
			if (schoolId && studentInfo.new_stage == 1) {
				title = "幼儿眼健康档案筛查结果通知单";
			} else if (schoolId && studentInfo.new_stage != 1) {
				title = "中小学校园眼健康档案筛查结果通知单"
			}
			if (schoolId) {
				printerJobs
					.print(tool.formatTime(new Date()))
					.print(printerUtil.fillLine())
					.setAlign('ct')
					.setSize(2, 2)
					.print('爱尔眼科')
					.setSize(1, 1)
					.setBold(true)
					.print(title)
					.print(printerUtil.fillLine());
			} else {
				printerJobs
					.print(tool.formatTime(new Date()))
					.print(printerUtil.fillLine())
					.setAlign('ct')
					.setSize(2, 2)
					.print('爱尔眼科')
					.setSize(1, 1)
					.print(title)
					.print(printerUtil.fillLine());
			}

			if (schoolId && studentInfo.hasOwnProperty("new_scnum")) {
				printerJobs.setSize(1, 1).setAlign('lt')
					.print(`筛查编号：${studentInfo.new_scnum}`);
			}

			for (let index in personInfo) {

				printerJobs.setSize(1, 1).setAlign('lt').print(personInfo[index]);
			}


			if (scinfo.iphoneno1) {
				printerJobs.setSize(1, 1).setAlign('lt')
					.print("联系电话：" + tool.replaceIDPhone(scinfo.iphoneno1, 3, 4))
			}
			if (scinfo.sfz) {
				printerJobs.setSize(1, 1).setAlign('lt')
					.print("身份证：" + tool.replaceIDPhone(scinfo.sfz, 3, 4))
			}
			if (scinfo.createdon) {
				//debugger;
				console.log(tool.formatDay(scinfo.createdon));
				printerJobs.setSize(1, 1).setAlign('lt')
					.print("筛查时间：" + tool.formatDay(scinfo.createdon))
			}

			printerJobs.setSize(1, 1).setAlign('lt')
				.print(printerUtil.inline("检查项目", "右眼  左眼"))

			//裸眼视力
			if (this.data.nakedEyeshow == true && this.data.nakedEye) {
				if (!schoolId) {
					printerJobs.setSize(1, 1).setAlign('lt').print("[视力检查]");
				}

				let nakedEye = this.data.nakedEye;
				let rightTxt = '裸眼视力';
				let leftTxt = nakedEye.visionRight;
				leftTxt += (nakedEye.nakedEyeRight ? '(' + nakedEye.nakedEyeRight + ')' : '');
				leftTxt += ' ' + nakedEye.visionLeft;
				leftTxt += (nakedEye.nakedEyeLeft ? '(' + nakedEye.nakedEyeLeft + ')' : '');

				if (schoolId) {
					leftTxt = nakedEye.visionRight + ' ' + nakedEye.visionLeft;
				}
				printerJobs.setSize(1, 1).setAlign('lt')
					.print(printerUtil.inline(rightTxt, leftTxt));
			}

			//矫正视力
			if (this.data.correctEyeshow == true && this.data.correctEye && !schoolId) {
				let correctEye = this.data.correctEye;
				let rightTxt = '矫正视力';
				let leftTxt = correctEye.visionRight + '   ' + correctEye.visionLeft;
				printerJobs.setSize(1, 1).setAlign('lt').print(printerUtil.inline(rightTxt, leftTxt));
			}

			//屈光检查
			if (this.data.refractiveexaminationshow && this.data.refractiveexamination) {
				printerJobs.setSize(1, 1).setAlign('lt').print("[屈光检查]");
				let refractiveexamination = this.data.refractiveexamination;
				if (refractiveexamination.optometryGlassesOrNot && !schoolId) {
					let rightTxt = '是否医学验光配镜';
					let leftTxt = refractiveexamination.optometryGlassesOrNot;
					printerJobs.setSize(1, 1).setAlign('lt').print(printerUtil.inline(rightTxt, leftTxt));
				}

				if (refractiveexamination.optometryGlassesOrNot && !schoolId) {
					let rightTxt = '佩戴眼镜';
					let leftTxt = refractiveexamination.wearGlassesOrNot;
					printerJobs.setSize(1, 1).setAlign('lt').print(printerUtil.inline(rightTxt, leftTxt));
				}

				if (refractiveexamination.myopiaOrNot && !schoolId) {
					let myopiaOrNot = refractiveexamination.myopiaOrNot;
					let myopiaYear = refractiveexamination.myopiaYear
					let rightTxt = '有无近视';
					let leftTxt = myopiaOrNot === '有' ? `${myopiaOrNot} ${myopiaYear}年` : "";
					printerJobs.setSize(1, 1).setAlign('lt')
						.print(printerUtil.inline(rightTxt, leftTxt));
				}

			}

			//屈光度数检查
			if (this.data.dioptertestshow) {
				if (!schoolId) {
					printerJobs.setSize(1, 1).setAlign('lt').print("[屈光度数检查]");
				}

				let dioptertest = this.data.dioptertest;
				if (dioptertest.sphericalDegreeRight || dioptertest.sphericalDegreeleft) {
					let rightTxt = schoolId ? '电脑验光' : '球面度数';
					let leftTxt = `${dioptertest.sphericalDegreeRight} ${dioptertest.sphericalDegreeleft}`;
					if (schoolId) {
						leftTxt = '';
						if (dioptertest.sphericalDegreeRight) {
							leftTxt += (dioptertest.sphericalDegreeRight * 100 > 0 ? `远视${dioptertest.sphericalDegreeRight*100}度` :
								`近视${dioptertest.sphericalDegreeRight*100*-1}度`);
						}
						if (dioptertest.sphericalDegreeleft) {
							leftTxt += (dioptertest.sphericalDegreeleft * 100 > 0 ? ` 远视${dioptertest.sphericalDegreeleft*100}度` :
								` 近视${dioptertest.sphericalDegreeleft*100*-1}度`);
						}

					}
					printerJobs.setSize(1, 1).setAlign('lt')
						.print(printerUtil.inline(rightTxt, leftTxt));
				}
				if (dioptertest.cylRight || dioptertest.cylLeft) {
					let rightTxt = schoolId ? '    ' : '散光';
					let leftTxt = `${dioptertest.cylRight} ${dioptertest.cylLeft}`;
					if (schoolId) {
						leftTxt = '';
						if (dioptertest.cylRight) {
							leftTxt += (dioptertest.cylRight * 100 > 0 ? `散光${dioptertest.cylRight*100}度` :
								`散光${dioptertest.cylRight*100*-1}度`);
						}
						if (dioptertest.cylLeft) {
							leftTxt += (dioptertest.cylLeft * 100 ? ` 散光${dioptertest.cylLeft*100}度` :
								` 散光${dioptertest.cylLeft*100*-1}度`);
						}
					}
					printerJobs.setSize(1, 1).setAlign('lt')
						.print(printerUtil.inline(rightTxt, leftTxt));
				}
				if (dioptertest.pupilDistance && !schoolId) {
					let rightTxt = '瞳距';
					printerJobs.setSize(1, 1).setAlign('lt')
						.print(printerUtil.inline(rightTxt, dioptertest.pupilDistance));
				}
				if (dioptertest.gazeMisalignment && !schoolId) {
					let rightTxt = '凝视不对称度';
					printerJobs.setSize(1, 1).setAlign('lt')
						.print(printerUtil.inline(rightTxt, dioptertest.gazeMisalignment));
				}
				if ((dioptertest.pupilSizeRight || dioptertest.pupilSizeLeft) &&
					!schoolId) {
					let rightTxt = '瞳孔大小';
					let leftTxt =`${dioptertest.pupilSizeRight} ${dioptertest.pupilSizeLeft}`;
					printerJobs.setSize(1, 1).setAlign('lt')
						.print(printerUtil.inline(rightTxt, leftTxt));
				}
				if ((dioptertest.astigmatismAxisRight || dioptertest.astigmatismAxisLeft) &&
					!schoolId) {
					let rightTxt = '散光轴度';
					let leftTxt =`${dioptertest.pupilSizeRight} ${dioptertest.pupilSizeRight}`;
					printerJobs.setSize(1, 1).setAlign('lt')
						.print(printerUtil.inline(rightTxt, leftTxt));
				}

			}

			//筛查判断
			if (this.data.scjudgeshow == true && !schoolId) {
				printerJobs.print(printerUtil.fillLine());
				printerJobs.setSize(1, 1).setAlign('lt').print("[筛查判断]");
				var scjudgeResult = this.data.scjudgeResult;
				var index = 1;
				scjudgeResult.forEach(function(item) {
					var txt = index + '.' + item.key + '：' + item.name
					printerJobs.setSize(1, 1).setAlign('lt').print(txt);
					index++;
				})
				printerJobs.print(printerUtil.fillLine());
			}

			//建议
			if (this.data.adviseshow == true && !schoolId) {
				var advise = this.data.advise;
				var head = '[' + advise.key + ']';
				printerJobs.setSize(1, 1).setAlign('lt').print(head);
				printerJobs.setSize(1, 1).setAlign('lt').print(advise.name);
			}

			printerJobs.println();

			if (!schoolId) {
				printerJobs.setAlign('lt').setSize(1, 1)
					.print('本结果仅筛查建议，非诊断依据')
					.print(printerUtil.fillLine())
					.print("爱尔眼科，共享全球眼科智慧")
					.print("预约咨询热线：400-008-009")
					.print("爱尔官网：www.aierchina.com")
				printerJobs.setAlign('lt').setSize(1, 1).setBold(true).print("扫一扫有惊喜哦:)").println();
			} else {
				let studentdnum = this.data.studentInfo.new_scnum ? this.data.studentInfo.new_scnum : '';
				printerJobs.setAlign('lt').setSize(1, 1)
					.print('本结果仅筛查建议，非诊断依据')
					.print(printerUtil.fillLine())
					.print('扫描二维码查询完整眼健康检查分析报告')
					.print('步骤：')
					.print("1.扫描二维码，并关注服务号")
					.print("2.点击界面提示中小学校园眼健康档案查询")
					.print(`3. 请输入筛查编号${studentdnum}，通过手机号码短信验证获取完整眼检查分析报告`)
					.println();
			}


			var buffer = printerJobs.buffer();
			let arrPrint = [];

			// 1.并行调用多次会存在写失败的可能性
			// 2.建议每次写入不超过20字节
			// 分包处理，延时调用
			const maxChunk = 20;
			const delay = 20;

			for (let i = 0, j = 0, length = buffer.byteLength; i < length; i += maxChunk, j++) {
				//debugger;
				let subPackage = buffer.slice(i, i + maxChunk <= length ? (i + maxChunk) : length);
				arrPrint.push(subPackage);
			}

			let qrcodebuffer = this.printQrcode();
			for (let i = 0; i < qrcodebuffer.length; i++) {
				//debugger;
				arrPrint.push(qrcodebuffer[i]);
			}

			for (let i = 0; i < arrPrint.length; i++) {
				//debugger;
				//setTimeout(this._writeBLECharacteristicValue, i * delay, arrPrint[i]);
				debugger;
				this._writeBLECharacteristicValue(arrPrint[i]);
			}

		},

		printQrcode() {

			let arrPrint = [];


			var buffer = util.hexStringToArrayBufferstr(qrcodetxt);
			//debugger;
			var datalen = (buffer.byteLength + 3);
			var pL = datalen & 0xff;
			var pH = datalen >> 8;

			arrPrint.push(util.sendDirective([0x1d, 0x28, 0x6b, 0x03, 0x00, 0x31, 0x43, 0x09]));
			arrPrint.push(util.sendDirective([0x1d, 0x28, 0x6b, 0x03, 0x00, 0x31, 0x45, 0x05]));
			arrPrint.push(util.sendDirective([0x1b, 0x61, 0x01]));
			arrPrint.push(util.sendDirective([0x1d, 0x28, 0x6b, pL, pH, 0x31, 0x50, 0x30]));
			for (let i = 0; i < buffer.byteLength; i = i + 20) {
				arrPrint.push(buffer.slice(i, i + 20));
			}

			arrPrint.push(util.sendDirective([0x1d, 0x28, 0x6b, 0x03, 0x00, 0x31, 0x51, 0x30]));
			arrPrint.push(util.sendDirective([0x1b, 0x61, 0x01]));

			arrPrint.push(util.hexStringToArrayBufferstr("\n"));
			arrPrint.push(util.hexStringToArrayBufferstr("\n"));
			arrPrint.push(util.hexStringToArrayBufferstr("\n"));

			return arrPrint;
		},
		//打印蓝牙设备显示
		handlePrint: function(e) {
            this.openBluetoothAdapter();
			this.setData({
				dialogShow: true
			});
		},

		//打印取消
		dialogClose: function(e) {
			this.setData({
				dialogShow: false
			});
		},

		//打印确认
		dialogConfirm: function(e) {
			this.writeBLECharacteristicValue();
			this.setData({
				dialogShow: false
			});
		},




		//建立设备链接
		createBLEConnection(e) {
			const ds = e.currentTarget.dataset
			const deviceId = ds.deviceId
			const name = ds.name
			if (!this.data.connected) {
				this._createBLEConnection(deviceId, name)
			} else {
				wx.showModal({
					title: '提示',
					content: '已经链接，如需重新链接请先断开',
					showCancel: false
				});
			}


		},



		//关闭链接
		closeBLEConnection() {
			wx.closeBLEConnection({
				deviceId: this.data.deviceId
			})
			this.setData({
				connected: false,
				chs: [],
				canWrite: false,
			})
		},



		//关闭蓝牙
		closeBluetoothAdapter() {
			wx.closeBluetoothAdapter()
			this._discoveryStarted = false
		},

		// 小程序在之前已有搜索过某个蓝牙设备，并成功建立连接，可直接传入之前搜索获取的 deviceId 直接尝试连接该设备
		createBLEConnectionWithDeviceId(e) {
			const device = this.data.lastDevice
			if (!device) {
				return
			}
			const index = device.indexOf(':');
			const name = device.substring(0, index);
			const deviceId = device.substring(index + 1, device.length);
			console.log('createBLEConnectionWithDeviceId', name + ':' + deviceId)
			wx.openBluetoothAdapter({
				success: (res) => {
					console.log('openBluetoothAdapter success', res)
					this._createBLEConnection(deviceId, name)
				},
				fail: (res) => {
					console.log('openBluetoothAdapter fail', res)
					if (res.errCode === 10001) {
						wx.showModal({
							title: '错误',
							content: '未找到蓝牙设备, 请打开蓝牙后重试。',
							showCancel: false
						})
						wx.onBluetoothAdapterStateChange((res) => {
							console.log('onBluetoothAdapterStateChange', res)
							if (res.available) {
								// 取消监听
								wx.onBluetoothAdapterStateChange(() => {});
								this._createBLEConnection(deviceId, name)
							}
						})
					}
				}
			})
		},

		_writeBLECharacteristicValue(buffer) {
			//debugger;
			wx.writeBLECharacteristicValue({
				deviceId: this._deviceId,
				serviceId: this._serviceId,
				characteristicId: this._characteristicId,
				value: buffer,
				success(res) {
					console.log('writeBLECharacteristicValue success', res)
				},
				fail(res) {
					console.log('writeBLECharacteristicValue fail', res)
				}
			})
		},

		/**
		 * 生命周期函数--监听页面初次渲染完成
		 */
		onReady: function() {

		},


		/**
		 * 生命周期函数--监听页面隐藏
		 */
		onHide: function() {
			//this.closeBluetoothAdapter();
		},

		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload: function() {
			this.closeBluetoothAdapter();
		},

		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh: function() {

		},

		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom: function() {

		},

		/**
		 * 用户点击右上角分享
		 */
		onShareAppMessage: function() {

		},

	}
})
